package com.ywxx.dyhelper.activity;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.pgyersdk.update.PgyUpdateManager;
import com.ywxx.dyhelper.BuildConfig;
import com.ywxx.dyhelper.R;
import com.ywxx.dyhelper.base.BaseAcitivity;
import com.ywxx.dyhelper.base.BaseRecyclerAdapter;
import com.ywxx.dyhelper.base.BaseRecyclerHolder;
import com.ywxx.dyhelper.model.ResponseModel;
import com.ywxx.dyhelper.utils.ConstAPI;
import com.ywxx.dyhelper.utils.ConstValues;
import com.ywxx.dyhelper.utils.DYVersionUtils;
import com.ywxx.dyhelper.utils.EncryptUtil;
import com.ywxx.dyhelper.utils.HttpUtils;
import com.ywxx.dyhelper.utils.ParamsHelper;

import java.util.ArrayList;
import java.util.HashMap;

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class MainActivity extends BaseAcitivity implements View.OnClickListener
{

    private TextView labAppName;
    private TextView labVersion;

    private RecyclerView lv;

    BaseRecyclerAdapter<HashMap<String, Object>> adapter;

    //功能菜单
    private ArrayList<HashMap<String, Object>> mData = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getSupportActionBar().hide();
        InitUI();

        DataToUI();
    }

    @Override
    protected void InitUI()
    {
        InitTitle();

        labAppName = findViewById(R.id.labAppName);
        labVersion = findViewById(R.id.labVersion);
        lv = findViewById(R.id.lv);

        labLeft.setText("关于");
        labRight.setText("设置");
        labLeft.setOnClickListener(this);
        labRight.setOnClickListener(this);
        //检查更新
        new PgyUpdateManager.Builder().setForced(true).register();


        getAppConfig();

        //检查解密
//        String str = "h8/7uo5E7JB94YYPBXmBcHZcaRnmPYsbhqbarRGjSN+njjiqV/zPErXzQUyUkj6kx/SMq+wuCfwbgFGxoL4P+pVDcgk8oCX2bSKrofzG4THo0Kfe9C0rl07O4O232f0WdMRs/+eCEJVgMoJp6Y2fHBwLWh8KLUYg3DIKb5cvPnh9huuZBryLIiHnlF/HE9owMKYQSRV/Tcw/jG8zEaaoebj3VoZFYU1HGUJYpc/7UYX+0HCXG6PKTiHQgunzkiWKXjP9j1MU7xS4ppN1JDV3luZmE/pJMh7Q13SR1tjBBskJNl9vfOkY+px8Q3pw0Qd1/N64rBkrc/zBiWSXNCPmWl4hG9auxgyFqFg0uloDxVaSFcFGmia+UK1uBkc3fS+lkAXRFWYda/JicXc4LvI/0+WN9NkKtUhTXyH/kIFUjozTLmJfz/8pa+ZRqnKoAqtRMAxlBhRAvbsF1IR1aKUOuNIBAI1QB9oB7mvHb6NPxiAdaDtNxcsojvLQ5Oz6qPI2qJqHSFHRgMBdcJ6bcHh3Cb2PxP5Ykq7jNcgkhsvEnJIhd8WlwanxhLLxe5E2ZcORdjE9mlG/YYclYhcrbBALOlhD3klZaB/9ZDU95eNEIx8LAUx6FyPMs9oVjAt8fPrmvrstltuadODw5CW2YgmRoVGdYL6c/R40mgJGd/wvlxHJbHpw1cx65pXUUWyZK+HFgL/HTLLhoc1i8Q20HGc+cl5at14WvdvPtW9B3v9GuDmfmEO0yt5nq6J9ny/bQdjApYNcui9OaD9jnYAMdkWl3Q==";
//        try
//        {
//            DYVersionUtils.ParseObjectConfig(ConstValues.getDyAPPVer(MainActivity.this), str);
//
//        } catch (Exception e)
//        {
//            e.printStackTrace();
//        }
    }

    /**
     * 获取APP配置文件
     */
    private void getAppConfig()
    {
        ParamsHelper params = new ParamsHelper(ConstAPI.版本ID配置);
        params.Add("dyVersion", ConstValues.getDyAPPVer(getApplicationContext()));

        new HttpUtils(params)
        {
            @Override
            public void onHttpResult(ResponseModel response)
            {
                if (response.status == 1)
                {
                    try
                    {
                        DYVersionUtils.ParseObjectConfig(ConstValues.getDyAPPVer(getApplicationContext()), response.data);
                    } catch (Exception e)
                    {
                        e.printStackTrace();
                        Toast.makeText(getApplicationContext(), "获取配置文件失败...", Toast.LENGTH_LONG).show();
                    }
                } else
                {
                    Toast.makeText(getApplicationContext(), response.msg, Toast.LENGTH_LONG).show();

                }
            }
        };


    }

    @Override
    protected void DataToUI()
    {
        labAppName.setText(getResources().getString(R.string.app_name) + "(" + BuildConfig.dz_name + ")");
        labVersion.setText(String.format("版本号:%s  |  抖音版本号:%s", BuildConfig.VERSION_NAME, ConstValues.getDyAPPVer(this)));
        mData.clear();
        //简化版
        if (BuildConfig.dz_power.equals("100"))
        {
            mData.add(getMenu("抖音养号", R.drawable.home_1, 1, KeepNoSettingAcitivity.class));
            mData.add(getMenu("万能引流", R.drawable.home_2, 2, UniversalDrainageActivity.class));
            mData.add(getMenu("一键取关", R.drawable.home_4, 4, CancelFollowActivity.class));
        }


        //简化版
        if (BuildConfig.dz_power.equals("110") && BuildConfig.DEBUG != true)
        {
            mData.add(getMenu("抖音养号", R.drawable.home_1, 1, KeepNoSettingAcitivity.class));
            mData.add(getMenu("万能引流", R.drawable.home_2, 2, UniversalDrainageActivity.class));
            mData.add(getMenu("一键取关", R.drawable.home_4, 4, CancelFollowActivity.class));
            mData.add(getMenu("一键识别", R.drawable.home_8, 8, RecognitionActivity.class));
            mData.add(getMenu("自动广告", R.drawable.home_7, 7, AutoAdvertisementActivity.class));
        }

        //旗舰版
        if (BuildConfig.dz_power.equals("120") || BuildConfig.DEBUG == true)
        {
            mData.add(getMenu("抖音养号", R.drawable.home_1, 1, KeepNoSettingAcitivity.class));
            mData.add(getMenu("万能引流", R.drawable.home_2, 2, UniversalDrainageActivity.class));
            mData.add(getMenu("精准引流", R.drawable.home_3, 3, PreciseDrainageActivity.class));
            mData.add(getMenu("一键取关", R.drawable.home_4, 4, CancelFollowActivity.class));

            if (BuildConfig.DEBUG)
            {
                mData.add(getMenu("一键关注", R.drawable.home_5, 5, CancelFollowActivity.class));
                mData.add(getMenu("一键回关", R.drawable.home_6, 6, CancelFollowActivity.class));
            }
            mData.add(getMenu("一键识别", R.drawable.home_8, 8, RecognitionActivity.class));
            mData.add(getMenu("自动广告", R.drawable.home_7, 7, AutoAdvertisementActivity.class));
        }
        mData.add(getMenu("一键已读", R.drawable.home_8, 9, ReadMessageActivity.class));

        adapter = new BaseRecyclerAdapter<HashMap<String, Object>>(this, mData, R.layout.layout_menu_item)
        {
            @Override
            public void convert(BaseRecyclerHolder holder, HashMap<String, Object> item, int position, boolean isScrolling)
            {
                holder.setText(R.id.labName, item.get("name").toString());
                holder.setImageResource(R.id.iv, (int) item.get("resid"));
            }
        };
        lv.setLayoutManager(new GridLayoutManager(this, 3));
        lv.setAdapter(adapter);

        adapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener()
        {
            @Override
            public void onItemClick(RecyclerView parent, View view, final int position)
            {
                if (BuildConfig.DEBUG == true || ConstValues.getBooleanValue(MainActivity.this, "first_guide", true))
                {
                    AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
                    dialog.setTitle("温馨提示");
                    dialog.setMessage("首次使用软件需要在首页界面观看一两分钟推荐视频采集数据");
                    dialog.setPositiveButton("确定", new DialogInterface.OnClickListener()
                    {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i)
                        {
                            ConstValues.SaveValue(MainActivity.this, "first_guide", false);
                            GoToNext(position);
                        }
                    });
                    dialog.setCancelable(false);
                    dialog.show();
                } else
                {
                    GoToNext(position);
                }
            }
        });


        //检测无障碍服务是否开启
        StartTaskServer(-1);

        startFloatingService();

    }

    private void GoToNext(int position)
    {
        HashMap<String, Object> map = mData.get(position);
        Intent intent = new Intent(MainActivity.this, (Class<?>) map.get("activity"));
        intent.putExtra("Title", map.get("name").toString() + "配置");
        intent.putExtra("TaskType", (int) map.get("tasktype"));
        startActivity(intent);
    }

    @SuppressLint("ShowToast")
    public void startFloatingService()
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this))
        {
            Toast.makeText(this, "当前无权限，请授权", Toast.LENGTH_SHORT);
            Intent intent = new Intent();
            intent.setAction(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivityForResult(intent, 0);
        }
    }

    private HashMap<String, Object> getMenu(String name, int resid, int tasktype, Class<?> activiObj)
    {
        HashMap<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("resid", resid);
        map.put("tasktype", tasktype);
        map.put("activity", activiObj);

        return map;
    }

    @Override
    public void onClick(View v)
    {
        if (v == labLeft)
        {
            AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            dialog.setTitle("公告");
            dialog.setMessage("软件免责申明:\r\n     \"" + getResources().getString(R.string.app_name) + "\"是一款集软件下载、更新、卸载优化于一体的引流营销工具。该软件仅供用户之间相互学习交流！不能用于任何商业通途！本产品中提供软件之著作权归软件作者所有。用户可以自由选择是否使用该软件。如果用户下载、安装、使用该软件，则表明用户信任该软件作者！");
            dialog.setPositiveButton("关闭", new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialogInterface, int i)
                {
                    dialogInterface.dismiss();
                }
            });
            dialog.show();
        } else if (v == labRight)
        {
            Uri packageURI = Uri.parse("package:" + BuildConfig.APPLICATION_ID);
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
            startActivity(intent);
        }

    }
}